package gold.digger;

import java.util.*;

/**
 * Created by fanzhenyu02 on 2020/6/27.
 * common problem solver template.
 */
public class LC166 {

    public String fractionToDecimal(int numerator, int denominator) {
        long num = numerator, dem = denominator;
        StringBuilder res = new StringBuilder();
        if ((num < 0 && dem > 0) || (num > 0 && dem < 0)) {
            res.append("-");
        }

        num = Math.abs(num);
        dem = Math.abs(dem);

        if (num > dem) {
            res.append((long) (num / dem));
            num %= dem;
        } else {
            res.append("0");
        }

        if (num == 0) {
            return res.toString();
        }

        Map<Long, Long> dict = new LinkedHashMap<>();
        while (num != 0) {
            if (dict.containsKey(num)) {// means that already exist loop.
                res.append(".");
                for (Map.Entry<Long, Long> entry : dict.entrySet()) {
                    if (entry.getKey() == num) {
                        break;
                    }
                    res.append(entry.getValue());
                }

                res.append("(").append(dict.get(num));
                long cur = num * 10 % dem;
                while (cur != num) {
                    res.append(dict.get(cur));
                    cur = cur * 10 % dem;
                }

                res.append(")");
                return res.toString();
            }

            dict.put(num, num * 10 / dem);
            num = num * 10 % dem;
        }

        res.append(".");
        for (Map.Entry<Long, Long> entry : dict.entrySet()) {
            res.append(entry.getValue());
        }

        return res.toString();
    }

    public static void main(String[] args) {
        LC166 an = new LC166();
        System.out.println(an.fractionToDecimal(-2147483648, 1));
    }
}
